<?php
/**
 * IG_Model_DbTable
 *
 * @author mmxie
 * @copyright Copyright (c) 2009 Green Shore (http://www.iwgame.com)
 * @version $Id: DbTable.php 1104 2011-12-21 08:00:36Z mmxie $
 */
class IG_Model_DbTable extends Zend_Db_Table
{
    protected $_rowsetClass = 'IG_Model_Rowset';

    protected $_dbConfig;

    protected static $_product = PRODUCT;

    public static function setProduct($product)
    {
        self::$_product = $product;
    }

    public function __construct($config = array(), $definition = null)
    {
        if (isset($this->_dbConfig)) {

            $iniConfig = new Zend_Config_Ini(
                APPLICATION_PATH . '/configs/' . self::$_product . '.config.ini',
                $this->_dbConfig
            );
            $iniConfig = $iniConfig->toArray();
            $config = ((array) $config) + array(self::ADAPTER => Zend_Db::factory($iniConfig['adapter'], $iniConfig));
        }
        self::setDefaultMetadataCache('lvan_cache');
        parent::__construct($config, $definition);
    }

    /**
     * @return string|array
     */
    public function getPrimary ()
    {
        return $this->_primary;
    }

    /**
     * 分页查询
     * @param array|Zend_Db_Table_Select $where
     * @param array $order
     * @param array|string $group
     * @return Zend_Paginator
     */
    public function fetchPaginator($where = null, $order = null, $group = null)
    {
        if (!($where instanceof Zend_Db_Table_Select)) {
            $select = $this->select();

            if ($where !== null) {
                $this->_where($select, $where);
            }

            if ($order !== null) {
                $this->_order($select, $order);
            }

            if ($group !== null) {
                $select->group($group);
            }
        } else {
            $select = $where;
        }

        $paginator = Zend_Paginator::factory($select);
        $front     = Zend_Controller_Front::getInstance();
        $paginator->setDefaultItemCountPerPage(
            $front->getRequest()->getParam('numPerPage',
                Zend_Registry::get('lvan_options')->pagesize)
        );
        $paginator->setCurrentPageNumber($front->getRequest()->getParam('page', 1));
        //var_dump($paginator->getCurrentPageNumber());exit;
        return $paginator;
    }

    /**
     * fetch model
     *
     * - fetchKeyPair ($columns, $where, $order, $group, $limit, $offset)
     * - fetchColumn  ( ... )
     * - fetchUnique  ( ... )
     * - fetchGroup   ( ... )
     * - fetchBoth    ( ... )
     * @param string $method
     * @param array $params
     */
    public function __call($method, $params)
    {
        if (substr($method, 0, 5) == 'fetch') {
            $model = 'PDO::FETCH'
                   . strtoupper(preg_replace('/([A-Z])/', '_$1', substr($method, 5)));

            if (!defined($model)) {
                throw new IG_Exception("未定义的常量($model), 不能使用($method)");
            }

            $select = $this->select();

            if (!empty($params[0])) {
                $select->from($this->_name, $params[0]);
            } else {
                $select->from($this->_name);
            }

            if (!empty($params[1])) {
                $this->_where($select, $params[1]);
            }

            if (!empty($params[2])) {
                $this->_order($select, $params[2]);
            }

            if (!empty($params[3])) {
                $select->group($params[3]);
            }

            if (!empty($params[4]) || !empty($params[5])) {
                $select->limit($params[4], $params[5]);
            }

            return $select->query(constant($model))->fetchAll();
        }

        throw new IG_Exception("未定义方法($method)");
    }


    public function fetchCount($where = null)
    {
        $select = $this->select()
                       ->from($this->_name, 'count(*)');

        if ($where !== null) {
            $this->_where($select, $where);
        }

        return $select->query()->fetchColumn();
    }

    public function insertDuplicate($data)
    {
        $query  = 'INSERT INTO `' . $this->_name . '` SET ';
        $query1 = $query2 = $bind = array();
        foreach ($data as $key => $val) {
            $query1[] = "`$key`=?";
            $query2[] = "`$key`=values(`$key`)";
            $bind[]   = $val;
        }

        $query .= implode(',', $query1)
                . ' ON DUPLICATE KEY UPDATE '
                . implode(',', $query2);

        $sth    = $this->getAdapter()->prepare($query);
        if ($sth->execute($bind)) {
            return $this->getAdapter()->lastInsertId();
        } else {
            return false;
        }
    }

    public function replace($data)
    {
        $query  = 'REPLACE `' . $this->_name . '` SET ';
        $query1 = $bind = array();
        foreach ($data as $key => $val) {
            $query1[] = "`$key`=?";
            $bind[]   = $val;
        }

        $query .= implode(',', $query1);
        $sth    = $this->getAdapter()->prepare($query);
        if ($sth->execute($bind)) {
            return $this->getAdapter()->lastInsertId();
        } else {
            return false;
        }
    }
}